package com.ujs.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ujs.eduservice.entity.EduSubject;
import com.ujs.eduservice.entity.EduTeacher;
import com.ujs.eduservice.entity.excel.SubjectData;
import com.ujs.eduservice.entity.subject.OneSubject;
import com.ujs.eduservice.entity.subject.TwoSubject;
import com.ujs.eduservice.listener.SubjectExcelListener;
import com.ujs.eduservice.mapper.EduSubjectMapper;
import com.ujs.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-08-06
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 课程分类列表树形结构
    @Override
    public List<OneSubject> getAllSubject() {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<EduSubject>().eq("parent_id", 0L);
        List<EduSubject> oneSubject = baseMapper.selectList(wrapper);
        if (oneSubject != null && oneSubject.size() > 0) {
            return getAllTwoSubject(oneSubject);
        }
        return null;
    }

    /**
     * 通过一级分类数据获取到所有二级分类
     *
     * @param oneSubject 一级分类
     * @return 结果
     */
    private List<OneSubject> getAllTwoSubject(List<EduSubject> oneSubject) {
        return oneSubject.stream().map(one -> {
            OneSubject oneSubject1 = new OneSubject();
            BeanUtils.copyProperties(one, oneSubject1);
            QueryWrapper<EduSubject> twoWrapper = new QueryWrapper<EduSubject>().eq("parent_id", one.getId());
            List<EduSubject> twoSubjects = baseMapper.selectList(twoWrapper);
            if (twoSubjects != null && twoSubjects.size() > 0) {
                List<TwoSubject> twoSubject = twoSubjects.stream().map(two -> {
                    TwoSubject twoSubject1 = new TwoSubject();
                    twoSubject1.setId(two.getId());
                    twoSubject1.setTitle(two.getTitle());
                    return twoSubject1;
                }).collect(Collectors.toList());
                oneSubject1.setChildren(twoSubject);
                return oneSubject1;
            }
            return oneSubject1;
        }).collect(Collectors.toList());
    }
}
